import 'package:dio/dio.dart';
import '../common/utils/cache.dart';
import 'baseUrl.dart';
import 'errorHandle.dart';

class ApiClient {
  final Dio _dio;
  final String _defaultToken = SharedPreferenceMixin.getToken();
  ApiClient({String baseUrl = BaseUrl.defaultBaseUrl})
      :
        // _dio = Dio(BaseOptions(baseUrl: _defaultBaseUrl)) {
        //   // if(_defaultToken!=""){
        //   //   _dio.options.headers['Authorization'] = 'Bearer $_defaultToken';
        //   // }
        //   /// 添加拦截器
        //   _dio.interceptors.add(TokenInterceptors());
        // }

        _dio = Dio(BaseOptions(
          baseUrl: BaseUrl.defaultBaseUrl,
          connectTimeout: const Duration(seconds: 100),
          sendTimeout: const Duration(seconds: 100),
          contentType: Headers.jsonContentType,
        )) {
    _dio.interceptors.add(TokenInterceptors());
  }

  Future<Map<String, dynamic>> getRequest(String endpoint,
      {Map<String, dynamic>? queryParameters, bool includeToken = true}) async {
    try {
      if (_defaultToken != "" && includeToken) {
        _dio.options.headers['Authorization'] = 'Bearer $_defaultToken';
      }
      var response = await _dio.get(
        endpoint,
        queryParameters: queryParameters,
      );

      Map<String, dynamic> responseData = response.data;
      return responseData;
    } catch (error) {
      print('Error during GET request: $error');
      rethrow;
    }
  }

  Future<Map<String, dynamic>> postRequest(String endpoint,
      {Map<String, dynamic>? data, bool includeToken = true}) async {
    try {
      if (_defaultToken != "" && includeToken) {
        _dio.options.headers['Authorization'] = 'Bearer $_defaultToken';
      }
      final response = await _dio.post(
        endpoint,
        data: data,
      );
      Map<String, dynamic> responseData = response.data;
      return responseData;
    } catch (error) {
      // 处理错误，例如日志记录或抛出自定义异常
      print('Error during POST request: $error');
      rethrow;
    }
  }

  Future<Map<String, dynamic>> postFromRequest(String endpoint,
      {Map<String, dynamic>? data, bool includeToken = true}) async {
    try {
      if (_defaultToken != "" && includeToken) {
        _dio.options.headers['Authorization'] = 'Bearer $_defaultToken';
      }
      FormData formData = FormData.fromMap(data!);
      final response = await _dio.post(
        endpoint,
        options: Options(
          contentType: 'multipart/form-data',
        ),
        data: formData,
      );
      Map<String, dynamic> responseData = response.data;
      return responseData;
    } catch (error) {
      print('################# Error during POST request: $error');
      rethrow;
    }
  }

  // 关闭Dio实例，释放资源
  void close() {
    _dio.close();
  }
}
